/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;

import com.db.*;
import com.exception.*;
import com.javabeans.*;
import com.model.*;
import com.util.*;
import java.sql.Connection;
import javax.servlet.RequestDispatcher;

/**
 *
 * @author Administrador
 */
public class Operaciones extends HttpServlet {

    HttpServletRequest request;
    HttpServletResponse response;
    HttpSession session;
    String msg = "";
    
    private String PAGE = "";
    private static final String ERROR_PAGE = "WEB-INF/error.jsp";
    private static final String ERROR_AJAX = "WEB-INF/errorAjax.jsp";
    boolean isForward = true; // inicializamos con forward....
    Usuario s_Usuario = null;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        this.request = request;
        this.response = response;
        session = request.getSession();
        int accion = Integer.parseInt(request.getParameter("accion"));        
        if(session.getAttribute("s_Usuario") != null){
            s_Usuario = (Usuario)session.getAttribute("s_Usuario");
            try{
                switch(accion){
                    case 1 : listMatriculas(); break;                         // accion = 1 = lista venta de matriculas habilitados
                    case 2 : newVentaMatricu(); break;                        // accion = 2 = nueva venta matricula
                    case 3 : cancelarVentaMatri(); break;                     // accion = 3 = cancela venta de matricula abilitada
                    case 4 : indexParametro(); break;                         // accion = 75 = inicio de parametro
                    case 5 : listarIsXfacultadMatricula(accion); break;       // accion = 76 = listamos el parametro
                    case 6 : listarIsXfacultadMatricula(accion); break;       // accion = 77 = update por facultad
                    default : System.out.println(" accion = "+accion+" no existe en Administracion.java"); throw new DataException("accion = "+accion+" no existe en Transacciones.java");
                }
            }catch(DataException e){
                throw new ServletException(e);
            }
        }else
            PAGE = "web/index.jsp?msg=Indentifiquese. La Session no existe!";
        if(PAGE.length() > 0){
            if(isForward){
                RequestDispatcher dispatch = request.getRequestDispatcher(PAGE);
                dispatch.forward(request,response);
            }else{
                response.sendRedirect(PAGE);
            }
        }
    }
    
    public void listMatriculas()throws DataException{
        // accion = 1 = lista venta de matriculas habilitados
        Connection c = null;
        try{
            c = Conector.getConexion();
            GestionManager gmanager = ManagerFactory.getGestionManagerInstance(c);
            VentaMatriculaManager vmmanager = ManagerFactory.getVentaMatriculaManagerInstance(c);
            request.setAttribute("gestiones", gmanager.getGestVigentesYfuturos());
            request.setAttribute("vms", vmmanager.getVentaMatriculasVigentes());
            PAGE = "WEB-INF/ADMINISTRATIVO/OPERACIONES/HabVentaMatricula/habilitados.jsp?idMenu=2&idSubMenu=1";
        }catch(DataException e){
            System.out.println(UtilDate.getDateTime()+" Administracion -> listMatriculas() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Administracion -> listMatriculas() DataException "+e.getMessage());
            PAGE = ERROR_PAGE;
        }catch(Exception ex){
            System.out.println(UtilDate.getDateTime()+" Operaciones -> listMatriculas() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Operaciones -> listMatriculas() Exception ex: "+ex.getMessage());
            PAGE = ERROR_PAGE;
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    
    public void newVentaMatricu()throws DataException{
        // accion = 2 = nueva venta matricula
        PAGE = "";
        Connection c = null;
        int idVentaMatricula = 0;
        try{
            int idGestion = Integer.parseInt(request.getParameter("idGestion"));
            String fechaIni = request.getParameter("fechaIni");
            String horaIni = request.getParameter("horaIni");
            String fechaFin = request.getParameter("fechaFin");
            String horaFin = request.getParameter("horaFin");
            fechaIni = UtilDate.convertirFechaNormal_A_fechaSql(fechaIni)+" "+horaIni;
            fechaFin = UtilDate.convertirFechaNormal_A_fechaSql(fechaFin)+" "+horaFin;
            float costo = Float.parseFloat(request.getParameter("costo"));            
            VentaMatricula vm = new VentaMatricula();
            vm.setFechaIni(fechaIni);
            vm.setFechaFin(fechaFin);
            vm.setCosto(costo);
            vm.setIdGestion(idGestion);
            vm.setIdUsuario(s_Usuario.getIdUsuario());
            vm.setActivo(true);            
            c = Conector.getConexion();
            c.setAutoCommit(false);
            GestionManager gmanager = ManagerFactory.getGestionManagerInstance(c);
            VentaMatriculaManager vmmanager = ManagerFactory.getVentaMatriculaManagerInstance(c);
            idVentaMatricula = vmmanager.getIdVentaMatricula();
            vm.setIdVentaMatricula(idVentaMatricula);
            vmmanager.saveVentaMatricula(vm);
            msg = "<p style='text-align:center;color:blue'>La habilitación de venta de matrícula se registró correctamente!</p>";
            this.showVentaMatriculasHab(vmmanager.getVentaMatriculasVigentes(), msg);
            c.commit();
        }catch(DataException e){
            SqlManager.rollBack(c);
            System.out.println(UtilDate.getDateTime()+" Operaciones -> newVentaMatricu() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Operaciones -> newVentaMatricu() DataException "+e.getMessage());
            PAGE = ERROR_PAGE;
        }catch(Exception ex){
            SqlManager.rollBack(c);
            System.out.println(UtilDate.getDateTime()+" Operaciones -> newVentaMatricu() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Operaciones -> newVentaMatricu() Exception ex: "+ex.getMessage());
            PAGE = ERROR_PAGE;
        }finally{
            SqlManager.setAutoCommit(c, true);
            SqlManager.closeConexion(c);
        }
    }
    
    public void cancelarVentaMatri()throws DataException{
        // accion = 3 = cancela venta de matricula abilitada
        PAGE = "";
        Connection c = null;
        try{
            int idVentaMatricula = Integer.parseInt(request.getParameter("idVentaMatricula"));
            c = Conector.getConexion();
            VentaMatriculaManager vmmanager = ManagerFactory.getVentaMatriculaManagerInstance(c);
            vmmanager.cancelarVentaMatricula(idVentaMatricula);
            msg = "<p style='text-align:center;color:blue'>se cancelo correctamente!</p>";
            this.showVentaMatriculasHab(vmmanager.getVentaMatriculasVigentes(), msg);
        }catch(DataException e){
            System.out.println(UtilDate.getDateTime()+" Operaciones -> cancelarVentaMatri() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Operaciones -> cancelarVentaMatri() DataException "+e.getMessage());
            PAGE = ERROR_PAGE;
        }catch(Exception ex){
            System.out.println(UtilDate.getDateTime()+" Operaciones -> cancelarVentaMatri() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Operaciones -> cancelarVentaMatri() Exception ex: "+ex.getMessage());
            PAGE = ERROR_PAGE;
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    
    private void showVentaMatriculasHab(List<VentaMatricula> vms, String msg)throws IOException{
        PrintWriter out = response.getWriter();
        out.println("<h2 class='decorado'>Venta de Matrículas Abilitadas para la gestión vigente y posterior</h2>");
        out.println(msg);
        out.println("<table class='miReporte' style='width: 100%'>");
        out.println("    <tr>");
        out.println("        <td style='text-align: right'><input type='button' class='boton' value='Nueva Venta Matrícula' onclick='$.fn.addVentaMatricula()'/></td>");
        out.println("    </tr>");
        out.println("</table>");
        out.println("<table class='tabla_decorado' style='width: 100%'>");
        out.println("    <thead>");
        out.println("        <tr>");
        out.println("            <th width='15%' class='th_decoradoRowspan'>CIUDAD</th>");
        out.println("            <th width='20%' class='th_decoradoRowspan'>FACULTAD</th>");
        out.println("            <th width='15%' class='th_decoradoRowspan'>GESTION</th>");
        out.println("            <th width='10%' class='th_decoradoRowspan'>ESTADO GESTION</th>");
        out.println("            <th width='10%' class='th_decoradoRowspan'>FECHA HORA INICIO</th>");
        out.println("            <th width='10%' class='th_decoradoRowspan'>FECHA HORA FIN</th>");
        out.println("            <th width='7%' class='th_decoradoRowspan'>ESTADO</th>");
        out.println("            <th width='5%' class='th_decoradoRowspan'>COSTO</th>");
        out.println("            <th width='8%' class='th_decoradoRowspan'>ACCION</th>");
        out.println("        </tr>");
        out.println("    </thead>");
        out.println("    <tbody>");
        int i = 1;
        String aux = "";
        for(VentaMatricula vm : vms){
            if(vm.getGestion().getEstado() == 1)
                aux = "VIGENTE";
            else
                aux = "EN ESPERA";
            out.println("<tr class='tr_decorado'>");
            out.println("    <td class='th_decorado'>"+vm.getGestion().getFacultad().getDepartamento().getNombre()+"</td>");
            out.println("    <td class='th_decorado'>"+vm.getGestion().getFacultad().getNombre()+"</td>");
            out.println("    <td class='th_decorado'>"+vm.getGestion().getNombre()+"</td>");
            out.println("    <td class='th_decorado'>"+aux+"</td>");
            out.println("    <td class='th_decorado'>"+vm.getFechaIni()+"</td>");
            out.println("    <td class='th_decorado'>"+vm.getFechaFin()+"</td>");
            out.println("    <td class='th_decorado'>"+((vm.isActivo())?"ACTIVO":"CANCELADO")+"</td>");
            out.println("    <td class='th_decorado'>"+UtilTransaccion.redondear(vm.getCosto(), 2)+"</td>");
            out.println("    <td class='td_decoradoDerecha' style='text-align: center'>");
            if(vm.isActivo()){
                out.println("   <input type='button' value='Cancelar' onclick='$.fn.cancelarVentaMatricula("+vm.getIdVentaMatricula()+")' class='botonRep' title='Pulsa aqui para cancelar la venta de matrícula'/>");
            }else 
                out.println("   &nbsp;");
            out.println("   </td>");
            out.println("</tr>");
            i++;
        }
        if(i == 1){
            out.write("<tr class='tr_decorado'>");
            out.write("     <td class='td_decorado' colspan='9' style='text-align:center'><span style='color:red'>No existen venta de matrículas habilitadas!</span></td>");
            out.write("</tr>");
        }
        out.println("</tbody>");
        out.println("</table>");
    }
    
    private void indexParametro() throws DataException{// accion <-- 4
        PAGE = "WEB-INF/ADMINISTRATIVO/OPERACIONES/entidad/index.jsp";
    }

    private void listarIsXfacultadMatricula(int accion) throws DataException { // accion <-- 5 listamos el parametro;6<-- update matricula
        Connection c = null;
        int idParametro = 0;
        boolean vmXfacultad = false;
        if(accion == 6){
            idParametro = Integer.parseInt(request.getParameter("idParametro"));
            vmXfacultad = Boolean.parseBoolean(request.getParameter("vmXfacultad"));
        }
        try{
            c = Conector.getConexion();
            ParametroManager pManager = ManagerFactory.getParametroManagerInstance(c);
            if(accion == 6){
                Parametro p = new Parametro();
                p.setIdParametro(idParametro);
                p.setVentaMatriculaXfacultad(vmXfacultad);
                pManager.updateParametro(p);
                if(vmXfacultad)
                    msg = "Se actualiz&oacute; corr&eacute;ctamente la venta de Matr&iacute;cula por Facultad.";
                else
                    msg = "Se actualiz&oacute; corr&eacute;ctamente la venta de Matr&iacute;cula General.";
                request.setAttribute("msg", msg);
            }
            
            request.setAttribute( "parametro", pManager.getParametro() );// enviamos el parametro
            PAGE = "WEB-INF/ADMINISTRATIVO/OPERACIONES/entidad/matriculaXfacultad/xfacultad.jsp?idMenu=2&idSubMenu=2&idOpcion=1";
        }catch(DataException e){
            System.out.println(UtilDate.getDateTime()+" Operaciones -> listarIsXfacultadMatricula() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Operaciones -> listarIsXfacultadMatricula() DataException "+e.getMessage());
            PAGE = ERROR_PAGE;
        }catch(Exception ex){
            System.out.println(UtilDate.getDateTime()+" Operaciones -> listarIsXfacultadMatricula() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Operaciones -> listarIsXfacultadMatricula() Exception ex: "+ex.getMessage());
            PAGE = ERROR_PAGE;
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
